<template>
  <div class="order-confirmation">
    <van-nav-bar
      title="订单确认"
      left-text="返回"
      left-arrow
      @click-left="onClickLeft"
    />
    <!-- 个人信息 -->
    <div class="personal-info">
      <el-row>
        <el-col :span="2">
          <i class="el-icon-location"></i>
        </el-col>
        <el-col :span="22">
          <div class="info" @click="toOrderCon()">
            <div class="name-phone">
              <span>姓名：{{user.name}}</span>
              <span>手机号：{{user.tel}}</span>
            </div>
            <p><span>收货地址：{{user.address}}</span></p>
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 商品信息 -->
    <div class="product-card" v-for="(pro, index) in product" :key="index">
      <img :src="pro.photo" alt="商品图片" class="product-image"/>
      <div class="product-details">
        <div class="product-name">{{ pro.comname }}</div>
        <div class="product-name">{{ pro.product }}</div>
        <div class="product-price">¥ {{ pro.price }}</div>
      </div>
    </div>

    <!-- 购买数量 -->
    <div class="quantity">
      <span>购买数量:</span>
      <div class="quantity-controls">
        <van-button plain @click="decreaseQuantity">-</van-button>
        <span>{{ quantity }}</span>
        <van-button plain @click="increaseQuantity">+</van-button>
      </div>
    </div>

    <!-- 总价和配送方式 -->
    <div class="summary">
      <div class="summary-item">
        <span>商品总价:</span>
        <span>¥ {{ totalProductPrice }}</span>
      </div>
      <div class="summary-item">
        <span>运费:</span>
        <span>¥ {{ shippingFee }}</span>
      </div>
      <div class="summary-item">
        <span>支付金额:</span>
        <span>¥ {{ totalAmount }}</span>  <!-- 显示支付金额 -->
      </div>
      <div class="summary-item">
        <span>配送方式:</span>
        <el-select v-model="deliveryMethod" @change="yunfei" placeholder="选择配送方式">
          <el-option label="快递运输" :value="1"></el-option>
          <el-option label="送货上门" :value="2"></el-option>
          <el-option label="客户自提" :value="3"></el-option>
        </el-select>
      </div>
    </div>

    <el-input
      type="textarea"
      placeholder="请填写订单备注"
      v-model="orderNote"
      rows="3"
    ></el-input>

    <div class="payment">
      <el-button type="primary" @click="submitOrder">提交订单</el-button>
    </div>
  </div>
</template>


<script>
import axios from "axios";

export default {
  data() {
    return {
      product: [],
      user: {},
      quantity: 1,
      orderNote: '',
      shippingFee: 0,
      deliveryMethod: '',
      idure: [],
      idur:[],
      totalProductPrice: 0, // 存储商品总价
      aid: '',
      admin:{},
    };
  },
  computed: {
    totalAmount() {
      return this.totalProductPrice + this.shippingFee; // 总金额 = 商品总价 + 运费
    },
    yunfei() {
      // 根据配送方式设置运费
      if (this.deliveryMethod === 1) { // 快递运输
        this.shippingFee = 10;
      } else if (this.deliveryMethod === 2) { // 送货上门
        this.shippingFee = 20;
      } else if (this.deliveryMethod === 3) { // 客户自提
        this.shippingFee = 0;
      }
    },
  },
  mounted() {
    this.idure = localStorage.getItem('idure');
    this.idur = localStorage.getItem('id');

    // 检查 idure 是否存在并执行 show3
    if (this.idure) {
      this.show3();
    }

    // 检查 idur 是否存在并执行 show1
    if (this.idur) {
      this.show1();
    }

    // 不论如何都执行 show2（如果需要）
    this.show2();
  },
  methods: {
    onClickLeft() {
      this.$router.go(-1)
    },
    toOrderCon() {
      this.$router.push('/shoppingaddress');
    },
    generateRandomNumber() {
      const randomNumber = Math.floor(1000000000 + Math.random() * 9000000000);
      return randomNumber.toString(); // 转换为字符串
    },
    increaseQuantity() {
      this.quantity++;
      this.calculateTotalPrice(); // 更新商品总价
    },
    decreaseQuantity() {
      if (this.quantity > 1) {
        this.quantity--;
        this.calculateTotalPrice(); // 更新商品总价
      }
    },
    show1() {
      axios.post(`/commodity/commodityshowlist?id=${this.idur}`).then(res => {
        this.product = res.data.data;
        this.calculateTotalPrice(); // 初始化计算总价
      });
    },
    show2() {
      axios.post('/addmanage/selectstatus').then(res => {
        this.user = res.data.data.addManage;
        this.name=this.user.name;
        this.tel=this.user.tel;
        this.address=this.user.address;
        localStorage.setItem("addressId",res.data.data.addManage.id)
      });
    },
    show3() {
      axios.post(`/shoppingcart/shoppingcartselectbyid?id=${this.idure}`).then(res => {
        this.product = res.data.data;
        this.calculateTotalPrice(); // 初始化计算总价
      });
    },
    submitOrder() {
      this.id =this.generateRandomNumber()
      localStorage.setItem('idusr', this.idure)
      localStorage.setItem('id', this.id)
      this.admin=JSON.parse(localStorage.getItem('admin'))
      axios.post(`/shoppingorder/shoppingorderadd?quantity=${this.quantity}&totalAmount=${this.totalAmount}&shippingFee=${this.shippingFee}&id=${this.id}&deliveryMethod=${this.deliveryMethod}&orderNote=${this.orderNote}&name=${this.name}&tel=${this.tel}&address=${this.address}&aid=${this.admin.id}`,
        this.product).then(res => {
        this.$router.push('/Payfororder')
      })
    },
    calculateTotalPrice() {
      this.totalProductPrice = this.product.reduce((total, pro) => {
        return total + (pro.price * this.quantity); // 计算商品总价
      }, 0);
    },
  },
};
</script>

<style scoped>
.order-confirmation {
  padding: 16px;
  max-width: 600px;
  margin: auto;
  padding-bottom: 120px; /* 给底部留出空间 */
  position: relative; /* 相对定位以支持内嵌元素的绝对定位 */
}

.title {
  text-align: center;
  margin-bottom: 20px;
}

.personal-info {
  background-color: #f9f9f9;
  border: 1px solid #e0e0e0;
  padding: 16px;
  margin-bottom: 20px;
}

.info {
  margin-top: 10px;
}

.name-phone {
  display: flex;
  justify-content: space-between;
}

.product-card {
  display: flex;
  align-items: center;
  padding: 16px;
  border: 1px solid #e0e0e0;
  margin-bottom: 20px;
}

.product-image {
  width: 80px;
  height: 80px;
  margin-right: 16px;
}

.product-details {
  flex: 1;
}

.quantity {
  display: flex;
  align-items: center;
  justify-content: space-between; /* 使内容左右对齐 */
  margin: 20px 0; /* 与其他元素分开 */
}

.quantity-controls {
  display: flex;
  align-items: center;
}

.summary {
  margin-top: 20px;
}

.summary-item {
  display: flex;
  justify-content: space-between;
  margin: 5px 0;
}

.payment {
  position: fixed; /* 固定在底部 */
  left: 0;
  right: 0;
  bottom: 0;
  background-color: white;
  padding: 16px;
  box-shadow: 0 -1px 5px rgba(0, 0, 0, 0.1);
  display: flex;
  justify-content: space-between;
  align-items: center;
  z-index: 1000; /* 确保在最上层 */
}
</style>
